const { getTable, setTable, getUnDelData } = require('../../database')
const { STATUS, TABLE } = require('../../utils/constants')
const { format } = require('../../utils/date')

// 根据 id 获取 role
async function getRole (req) {
  const id = Number.parseInt(req.params.id)
  const roles = await getTable(TABLE.ROLE)

  const role = roles.find(v => v.id === id)

  if (!role) {
    throw new Error('角色不存在')
  }

  return { roles, role }
}

// 获取角色列表
exports.getRoles = async (req, res, next) => {
  let { page, limit, name, status } = req.query
  page = page ? Number.parseInt(page) : 1
  limit = limit ? Number.parseInt(limit) : 10
  status = ['0', '1'].includes(status) ? Number.parseInt(status) : null

  try {
    let list = await getTable(TABLE.ROLE)
    const mens = await getUnDelData(TABLE.MENU)

    // 筛选
    list = list.filter(v => {
      const filterName = name ? v.name.includes(name) : true
      const filterStatus = status !== null ? v.status === status : true

      return filterName && filterStatus && v.isDel === 0
    })

    // 总条数
    const count = list.length

    // 排序并截取
    list = list.sort((a, b) => {
      return b._addTime - b._addTime
    }).slice((page - 1) * limit, page * limit)

    // 处理数据
    list = list.map(role => {
      role.menus = mens.filter(v => role.menus.includes(v.id)).map(v => ({
        id: v.id,
        name: v.name
      }))
      role._addTime = format(role._addTime)
      role._updateTime = format(role._updateTime)
      return role
    })

    // 响应结果
    res.json({
      status: STATUS.SUCCESS,
      data: {
        list,
        count
      }
    })
  } catch (error) {
    next(error)
  }
}

// 添加角色
exports.createRole = async (req, res, next) => {
  const { menus, status, name } = req.body

  try {
    const roles = await getTable(TABLE.ROLE)

    // 验证角色是否存在
    if (roles.some(v => v.name === name)) {
      next(`角色"${name}"已存在`)
      return
    }

    // 生成 id 自增
    let id = 1
    if (roles.length > 0) {
      const roleIds = roles.map(v => v.id).sort()
      id = roleIds[roleIds.length - 1] + 1
    }

    const now = Date.now()

    const role = {
      id,
      name,
      menus,
      status,
      isDel: 0,
      _addTime: now,
      _updateTime: now
    }

    roles.push(role)

    await setTable(TABLE.ROLE, roles)

    // 响应结果
    res.json({
      status: STATUS.SUCCESS,
      msg: 'ok'
    })
  } catch (error) {
    next(error)
  }
}

// 修改角色
exports.updateRole = async (req, res, next) => {
  const { menus, status, name } = req.body

  try {
    const { roles, role } = await getRole(req)

    role.menus = menus
    role.status = status
    role.name = name
    role._updateTime = Date.now()

    await setTable(TABLE.ROLE, roles)

    // 响应结果
    res.json({
      status: STATUS.SUCCESS,
      msg: 'ok'
    })
  } catch (error) {
    next(error)
  }
}

// 获取角色
exports.getRole = async (req, res, next) => {
  try {
    const { role } = await getRole(req)
    const mens = await getUnDelData(TABLE.MENU)

    role.menus = mens.filter(v => role.menus.includes(v.id)).map(v => ({
      id: v.id,
      name: v.name
    }))
    role._addTime = format(role._addTime)
    role._updateTime = format(role._updateTime)

    // 响应结果
    res.json({
      status: STATUS.SUCCESS,
      data: role
    })
  } catch (error) {
    next(error)
  }
}

// 删除角色
exports.deleteRole = async (req, res, next) => {
  try {
    const { roles, role } = await getRole(req)

    role.isDel = 1
    role._updateTime = Date.now()
    await setTable(TABLE.ROLE, roles)

    // 响应结果
    res.json({
      status: STATUS.SUCCESS,
      msg: 'ok'
    })
  } catch (error) {
    next(error)
  }
}

// 修改角色状态
exports.setRoleStatus = async (req, res, next) => {
  const status = Number.parseInt(req.params.status)

  try {
    const { roles, role } = await getRole(req)

    role.status = status
    role._updateTime = Date.now()
    await setTable(TABLE.ROLE, roles)

    // 响应结果
    res.json({
      status: STATUS.SUCCESS,
      msg: 'ok'
    })
  } catch (error) {
    next(error)
  }
}
